package com.company.management.utils;

import cn.hutool.core.io.FileUtil;
import lombok.extern.slf4j.Slf4j;
import com.company.framework.common.constants.TokenConstants;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.server.reactive.ServerHttpRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

@Slf4j
/**
 * @author wangzh
 * @Description:
 * @date 2021/4/28 10:03
 */
public class ServletUtils {
    /**
     * url 输出文件流
     *
     * @param path
     * @param response
     * @throws IOException
     */
    public static void fileStreamOut(Path path, HttpServletResponse response) throws IOException {
        byte[] bytes = FileUtil.readBytes(path);
        // 获取文件的 MIME 类型
        String mimeType = Files.probeContentType(path);
        response.setContentType(mimeType != null ? mimeType : "application/octet-stream");
        // 判断文件类型，如果是需要下载的类型，设置为 attachment，其他设置为 inline
        if (mimeType != null && (mimeType.equals("application/zip") || mimeType.equals("application/x-zip-compressed"))) {
            // 设置为下载附件
            response.setHeader("Content-Disposition", "attachment; filename=\"" + path.getFileName() + "\"");
        } else {
            // 如果是图片或其他可以直接预览的文件，设置为 inline
            response.setHeader("Content-Disposition", "inline; filename=\"" + path.getFileName() + "\"");
        }
        response.setContentLength((int) path.toFile().length());
        response.getOutputStream().write(bytes);
        response.getOutputStream().flush();
    }
    /**
     * 获取请求token
     */
    public static String getToken(HttpServletRequest request)
    {
        String token = request.getHeader(TokenConstants.TOKEN);
        return token;
    }
}
